import { Trans, withI18n } from '@lingui/react'
import { Alert, Button, Divider, Layout, Modal as antdModal } from 'antd'
import { Page } from 'components'
import { connect } from 'dva'
import PropTypes from 'prop-types'
import { stringify } from 'qs'
import React, { PureComponent } from 'react'
import { router } from 'utils'
import DeleteModal from './components/DeleteModal'
import Filter from './components/Filter'
import List from './components/List'
import Modal from './components/Modal'
import ProjectModel from './components/ProjectModel'
import Projectslist from './components/Projectslist'
import CreateModal from './components/CreateModal'
import RemoverbModal from './components/RemoverbModal'
import WorkerModal from './components/WorkerModal'
import Workers from './components/Workers'
import ProjectCreateModal from './components/ProjectCreateModal'

const ButtonGroup = Button.Group
const { Content } = Layout
const confirm = antdModal.confirm

@withI18n()
@connect(({ devices, app, loading }) => {
  const { isMobile } = app
  return { user: devices, isMobile, loading }
})
class User extends PureComponent {
  componentDidMount() {
    if (
      this.props.user &&
      this.props.user.projects &&
      this.props.user.projects.length > 0
    ) {
    } else {
      this.props.dispatch({
        type: 'devices/projects',
      })
    }
    if (
      this.props.user &&
      this.props.user.devicesoperate &&
      this.props.user.devicesoperate.deletedeivces != undefined
    ) {
    } else {
      this.props.dispatch({
        type: 'devices/initdevicesoperate',
      })
    }
  }
  render() {
    const { location, dispatch, isMobile, user, loading, i18n } = this.props
    // const { isMobile } = app
    const { query, pathname } = location
    const {
      list,
      pagination,
      modalVisible,
      projectmodalVisible,
      deletemodalVisible,
      createmodalVisible,
      movetorbmodalVisible,
      selectedRowKeys,
      projects,
      choosedproject,
      modelusers,
      distributeresult,
      reprojectresult,
      movetorbresult,
      devicesoperate, //包含用户可操作内容，以及全局静态数据
      deleteresult,
      canedit,
      workerModalVisible,
      workerSetWorkerresult,
      createProjectVisible,
    } = user
    const refreshproject = () => {
      this.props.dispatch({
        type: 'devices/projects',
      })
    }
    const handleRefresh = newQuery => {
      router.push({
        pathname,
        search: stringify(
          {
            ...query,
            ...newQuery,
          },
          { arrayFormat: 'repeat' }
        ),
      })
    }

    const createmodalProps = {
      visible: createmodalVisible,
      maskClosable: true,
      title: i18n.t`Create Device`,
      createloading: loading.effects[`devices/createdevice`],
      centered: true,
      projects,
      FirmwareVersions: devicesoperate ? devicesoperate.FirmwareVersions : [],
      onCreate: values => {
        dispatch({ type: 'devices/createdevice', payload: values }).then(() => {
          refreshproject()
          handleRefresh()
          dispatch({ type: 'devices/hidecreatemodal' })
        })
      },
      onCancel: () => {
        dispatch({ type: 'devices/hidecreatemodal' })
      },
    }

    const deletemodalProps = {
      visible: deletemodalVisible,
      maskClosable: true,
      title: i18n.t`Delete devices`,
      centered: true,
      selected: selectedRowKeys,
      devices: list,
      deleteresult,
      deleteloading: loading.effects[`devices/deleteimeidevices`],
      onCancel: () => {
        dispatch({ type: 'devices/hidedeletemodal' })
      },
      onDelete: items => {
        let imeis = ','
        for (let item in items) {
          let targ = items[item]
          if (targ && targ.Imei) imeis += targ.Imei + ','
        }
        imeis = imeis.slice(1, imeis.length - 1)
        confirm({
          title: i18n.t`Are you sure to delete these devices?`,
          content: i18n.t`All Imei ${imeis} user devices will be deleted, please operate with caution!`,
          okText: i18n.t`Yes`,
          okType: 'danger',
          cancelText: i18n.t`No`,
          onOk() {
            let selects = []
            for (let item in items) {
              let targ = items[item]
              if (targ && targ.objectId) selects.push(items[item].objectId)
            }
            dispatch({
              type: 'devices/deleteimeidevices',
              payload: { deviceids: selects },
            }).then(() => {
              dispatch({
                type: 'devices/updateState',
                payload: {
                  selectedRowKeys: [],
                },
              })
              handleRefresh()
              refreshproject()
            })
          },
        })
      },
    }

    const movetorbmodalProps = {
      visible: movetorbmodalVisible,
      maskClosable: true,
      title: i18n.t`Remove To Recycle Bin`,
      centered: true,
      selected: selectedRowKeys,
      devices: list,
      movetorbresult,
      movetorbloading: loading.effects[`devices/movetorb`],
      onCancel: () => {
        dispatch({ type: 'devices/hidemovetorbmodal' })
      },

      onMove: items => {
        let names = ','
        // console.log('items:' + JSON.stringify(items))
        for (let item in items) {
          let targ = items[item]
          // console.log('item:' + JSON.stringify(items[item]))
          if (targ && targ.DeviceName) names += targ.DeviceName + ','
        }
        names = names.slice(1, names.length - 1)
        confirm({
          title: i18n.t`Are you sure you want to put these devices to recycle bin?`,
          content: (
            <span>
              <b>{i18n.t`All devices that move to the recycling bin will not receive data reports`}</b>
              <br />
              {i18n.t`Include:`}&nbsp;{names}
            </span>
          ),
          okText: i18n.t`Yes`,
          okType: 'danger',
          cancelText: i18n.t`No`,
          onOk() {
            let selects = []
            for (let item in items) {
              let targ = items[item]
              if (targ && targ.objectId) selects.push(targ.objectId)
            }
            dispatch({
              type: 'devices/movetorb',
              payload: { deviceids: selects },
            }).then(() => {
              dispatch({
                type: 'devices/updateState',
                payload: {
                  selectedRowKeys: [],
                },
              })
              handleRefresh()
              refreshproject()
            })
          },
        })
      },
    }
    const projectslistProps = {
      handleRefresh,
    }
    const projectmodalProps = {
      visible: projectmodalVisible,
      maskClosable: true,
      // queryuserloading: loading.effects['devices/finduser'],
      confirmLoading: loading.effects[`devices/reproject`],
      title: i18n.t`Change the project`,
      centered: true,
      projects,
      selected: selectedRowKeys,
      devices: list,
      reprojectresult,
      onOk(data) {
        dispatch({
          type: `devices/reproject`,
          payload: data,
        }).then(() => {
          dispatch({
            type: 'devices/updateState',
            payload: {
              selectedRowKeys: [],
            },
          })
          refreshproject()
          handleRefresh()
        })
      },
      onCancel() {
        dispatch({
          type: 'devices/hideprojectmodal',
        })
      },
    }
    //❤️🧡💛💚💙💜💗💍🎉✨🎀🌸🌹🌺🍀🌟⚡🌞☔💦🌈🙃😝😜👑🍀🌴🌵🌷🌻💐🌾🍁🍂🍃🐭🐹
    const workermodalProps = {
      visible: workerModalVisible,
      maskClosable: true,
      queryuserloading: loading.effects['devices/finduser'],
      confirmLoading: loading.effects[`workers/projectSetWorkers`],
      title: i18n.t`Selecting Users`,
      centered: true,
      finduser: str => {
        dispatch({
          type: `devices/finduser`,
          payload: {
            name: str,
          },
        })
      },
      users: modelusers,
      workerSetWorkerresult,
      onOk: data => {
        dispatch({
          type: `devices/projectSetWorkers`,
          payload: data,
        })
      },
      onCancel() {
        dispatch({
          type: 'devices/hideModal',
        })
      },
    }

    // const projectcreatemodalProps = {

    // }
    const modalProps = {
      visible: modalVisible,
      maskClosable: true,
      queryuserloading: loading.effects['devices/finduser'],
      confirmLoading: loading.effects[`devices/distribute`],
      title: i18n.t`Distribution`,
      centered: true,
      finduser: str => {
        dispatch({
          type: `devices/finduser`,
          payload: {
            name: str,
          },
        })
      },
      users: modelusers,
      selected: selectedRowKeys,
      devices: list,
      distributeresult,
      onOk: data => {
        dispatch({
          type: `devices/distribute`,
          payload: data,
        }).then(() => {
          // handleRefresh()
        })
      },
      onCancel() {
        dispatch({
          type: 'devices/hideModal',
        })
      },
    }

    const listProps = {
      isMobile,
      canedit,
      choosedproject,
      dataSource: list,
      loading: loading.effects['devices/query'],
      pagination,
      onChange(page, pageSize) {
        handleRefresh({
          page: page,
          pageSize: pageSize,
        })
      },
      onRecovery: item => {
        dispatch({
          type: 'devices/rbrestore',
          payload: { deviceid: item.objectId },
        }).then(() => {
          dispatch({
            type: 'devices/updateState',
            payload: {
              selectedRowKeys: [],
            },
          })
          handleRefresh()
          refreshproject()
        })
      },
      onDeleteItem(id) {
        dispatch({
          type: 'devices/delete',
          payload: id,
        }).then(() => {
          handleRefresh({
            page:
              list.length === 1 && pagination.current > 1
                ? pagination.current - 1
                : pagination.current,
          })
        })
      },
      onEditItem(item) {
        router.push({
          pathname: `/devices/${item.objectId}`,
          search: stringify(location.query, { arrayFormat: 'repeat' }),
        })
      },
      ...(choosedproject == 'recycle'
        ? {}
        : {
            rowSelection: {
              selectedRowKeys,
              onChange: keys => {
                dispatch({
                  type: 'devices/updateState',
                  payload: {
                    selectedRowKeys: keys,
                  },
                })
              },
            },
          }),
    }

    const filterProps = {
      choosedproject,
      devicesoperate,
      query,
      onSearch(value) {
        handleRefresh({
          ...value,
        })
      },
    }

    // const handleDeleteItems = () => {
    //   dispatch({
    //     type: 'devices/multiDelete',
    //     payload: {
    //       ids: selectedRowKeys,
    //     },
    //   }).then(() => {
    //     handleRefresh({
    //       page:
    //         list.length === selectedRowKeys.length && pagination.current > 1
    //           ? pagination.current - 1
    //           : pagination.current,
    //     })
    //   })
    // }

    const handledistribut = e => {
      dispatch({
        type: 'devices/showModal',
        payload: {},
      })
    }

    const handlereproject = e => {
      // console.log("call project")
      dispatch({
        type: 'devices/showprojectmodal',
        payload: {},
      })
    }
    const handledeletedevices = e => {
      dispatch({
        type: 'devices/showdeletemodal',
      })
    }
    const handledcreate = e => {
      dispatch({
        type: 'devices/showcreatemodal',
      })
    }
    const handlemovetorb = e => {
      dispatch({
        type: 'devices/showmovetorbmodal',
      })
    }
    let length = selectedRowKeys.length
    return (
      <Page inner>
        <Content>
          <Layout style={{ padding: '0px 0', background: '#fff' }}>
            <Projectslist {...projectslistProps} />
            <Content style={{ padding: 0 }}>
              {devicesoperate && devicesoperate.cansearch && <Workers />}
              {devicesoperate && devicesoperate.cansearch && (
                <Filter {...filterProps} />
              )}
              {devicesoperate && devicesoperate.cansearch && (
                <Divider style={{ marginTop: '10px', marginBottom: '0px' }} />
              )}
              <ButtonGroup
                style={{
                  marginLeft: '0px',
                  marginRight: '0px',
                  marginBottom: '10px',
                  marginTop: '10px',
                }}
              >
                {devicesoperate && devicesoperate.candistribute && (
                  <Button disabled={length <= 0} onClick={handledistribut}>
                    <Trans>Distribution</Trans>
                  </Button>
                )}
                {devicesoperate && devicesoperate.canreproject && (
                  <Button disabled={length <= 0} onClick={handlereproject}>
                    <Trans>Change Project</Trans>
                  </Button>
                )}
                {devicesoperate && devicesoperate.canmovetorecycle && (
                  <Button disabled={length <= 0} onClick={handlemovetorb}>
                    <Trans>Move To Recycle Bin</Trans>
                  </Button>
                )}
                {devicesoperate && devicesoperate.deletedeivces && (
                  <Button
                    disabled={length <= 0}
                    type="danger"
                    onClick={handledeletedevices}
                  >
                    <Trans>Application for deletion</Trans>
                  </Button>
                )}
                {devicesoperate && devicesoperate.createdevices && (
                  <Button onClick={handledcreate}>
                    <Trans>Create</Trans>
                  </Button>
                )}
                {length > 0 && (
                  <Alert
                    style={{ marginTop: '2px' }}
                    message={<Trans>{`Selected ${length} items`}</Trans>}
                  />
                )}
              </ButtonGroup>
              <List {...listProps} />
            </Content>
          </Layout>
        </Content>
        {modalVisible && <Modal {...modalProps} />}
        {createProjectVisible && <ProjectCreateModal />}
        {workerModalVisible && <WorkerModal {...workermodalProps} />}
        {projectmodalVisible && <ProjectModel {...projectmodalProps} />}
        {deletemodalVisible && <DeleteModal {...deletemodalProps} />}
        {createmodalVisible && <CreateModal {...createmodalProps} />}
        {movetorbmodalVisible && <RemoverbModal {...movetorbmodalProps} />}
      </Page>
    )
  }
}
User.propTypes = {
  user: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default User
